/**
 * Created by mengw on 2017/7/10.
 */
// var baseUrl = "http://115.159.107.47:8888/smartJ/";
// var baseUrl = "http://123.206.228.129:8888/smartJ/";
// var baseUrl = "http://192.168.0.104:8888/smartJ/";
var baseUrl = "http://123.206.228.129:8888/smartJ/";
var baseQuestionUrl = baseUrl + "question/";
var baseQuestionnaireUrl = baseUrl + "questionnaire/";
var baseDeviceUrl = baseUrl + "device/";
var baseDealerUrl = baseUrl + "dealer/";
var baseRegionUrl = baseUrl + "region/";
var baseStatisticalUrl = baseUrl + "statistical/";
// var baseUrl = "http://127.0.0.1:8888/smartJ/";
// var baseQuestionUrl = baseUrl + "question/";
// var baseQuestionnaireUrl = baseUrl + "questionnaire/";
// var baseDeviceUrl = baseUrl + "device/";
// var baseDealerUrl = baseUrl + "dealer/";
// var baseRegionUrl = baseUrl + "region/";
// var baseStatisticalUrl = baseUrl + "statistical/";
var cookieName = "smartJCookie";
var shangchuandizhi="../tmp/p1.png"

/**
 * 登陆相关操作
 */
function login() {
    var url = baseUrl + "login/";
    var account = $("#account").val();
    var password = $("#password").val();
    var data = JSON.stringify({"account": account, "password": password});
    ajaxCommon.request('post',url,data,function (res) {
        if (res.data.state) {
            createCookie(cookieName, res.data.token);
            $(location).attr('href', 'index.html');
        } else {
            swal("登陆失败");
        }
    });
}

/**
 * 退出登录
 */
function loginOut() {
    var url = baseUrl + "login/logout";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        type: "GET",
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        contentType: "application/json",
        success: function (data) {
            $(location).attr('href', 'login.html');
        },
        error: function (request, error) {
            swal(error);
        }
    }));
}

/**
 * 判断数据对象是否为空
 * @param obj
 * @returns {boolean}
 */
function isNull(obj) {
    return obj === null || obj === "" || obj === undefined;
}

/**
 * 格式化日期
 * @param date
 * @param time
 * @returns {string}
 */
function formatDate(date, time) {
    date.setTime(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    return year + "-" + formNumber(month) + "-" + formNumber(day) + " " + formNumber(hours) + ":" + formNumber(minutes);
}

function formatDate1(time) {
    var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    return year + "-" + formNumber(month) + "-" + formNumber(day) + " " + formNumber(hours) + ":" + formNumber(minutes) + ":" + formNumber(seconds);
}

function formNumber(number) {
    if (number >= 0 && number < 10) {
        return "0" + number;
    } else {
        return number;
    }
}

/**
 * 唤起时间选择器
 */
function showDateTimePicker(objs) {
    for (var index in objs) {
        objs[index].datetimepicker({
            format: 'yyyy-mm-dd hh:ii'
        });
    }
}

/**
 * 以空白符分隔字符串
 * @param str
 * @returns {Array|*}
 */
function split(str) {
    return src.split(/(\s+)/g);
}

/**
 * 去除两端的空白符
 * @param str
 */
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 将字符串数组以指定的格式拼接在一起
 */
function strBuffAdd(strings, separator) {
    var string = "";
    for (var i = 0; i < strings.length; i++) {
        if (i !== strings.length - 1) {
            string += strings[i] + separator;
        } else {
            string += strings[i];
        }
    }
    return string;
}

/**
 * 解析URL中的参数并以数组返回
 * @param url
 * @returns {Array}
 */
function parseUrl(url) {
    var array = [];
    var str = url.split("?");
    var params;
    if (str.length > 1) {
        params = str[1].split("&");
        for (var index in params) {
            var param = params[index].split("=");
            var baseEntity = new BaseEntity(param[0], param[1]);
            array.push(baseEntity);
        }
        return array;
    } else {
        return null;
    }
}

function getParams(type){
    var url = location.href.split("?") ? location.href.split("?")[1] : '';
    var obj={};
    if(url){
        if(url.split('&')) {
            var arr = url.split('&')
            arr.map(function (item) {
                var name = item.split('=')[0]
                obj[name] = item.split('=')[1]
            })
        }else{
            obj[url.split('=')[0]] = url.split('=')[1]
        }
        return obj[type]
    }
}

/**
 * 给Ajax请求加上等待标识
 * @type {{buildLoadingOption: ajaxCommon.buildLoadingOption}}
 */
var ajaxCommon = {
    loadingHtml: '<div class="loader" id="loadingImgBox" style="width:100px;height:100px;position: absolute;left: 0;right:0;top:0;bottom:0;margin:auto;background:rgba(0,0,0,0.6);border-radius: 5px;text-align: center;color: #fff;line-height: 100px;z-index:9999;"><div class="loader-inner line-spin-fade-loader"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div></div>',

    buildLoadingOption: function (option) {
        var _this = this;
        var loadingAjaxOption = {
            beforeSend: function () {
                $("#loadingImgBox").remove();
                $('body').append(_this.loadingHtml);
            },
            complete: function () {
                $("#loadingImgBox").remove();
            },
            error: function () {
                $("#loadingImgBox").remove();
            }
        };

        for (var key in option) {
            loadingAjaxOption[key] = option [key];
        }
        return loadingAjaxOption;
    },

    /**
     * 正常ajax 请求封装
     * @author beibei  2018/12/21
     * @param type  post、get、delete
     * @param url   请求地址
     * @param data  请求参数
     * @param callbackSucc  请求成功回调
     * @param callbackErr   请求失败回调
     */
    request:function(type,url,data,callbackSucc,callbackErr){
        var _this = this;
        $.ajax({
            url: url,
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: type,
            contentType: "application/json",
            data: data,
            beforeSend: function () {
                $("#loadingImgBox").remove();
                $('body').append(_this.loadingHtml);
            },
            success: function (res) {
                $("#loadingImgBox").remove();
                if(callbackSucc !== undefined) {
                    callbackSucc(res)
                }else{
                    swal(res.message)
                }
            },
            error: function (res) {
                $("#loadingImgBox").remove();
                if(callbackErr !== undefined) {
                    if (res.status === 401) {
                        setTimeout(function(){
                            $(location).attr('href', 'login.html');
                        },2000)
                    }
                    callbackErr(res)
                }else{
                    if (res.status === 401) {
                        setTimeout(function(){
                            $(location).attr('href', 'login.html');
                        },2000)
                    } else {
                        swal();
                    }
                }
            }
        })
    },

    /**
     * 文件上传ajax 请求封装
     * @author beibei  2018/12/21
     * @param type  post、get、delete
     * @param url   请求地址
     * @param data  请求参数
     * @param callbackSucc  请求成功回调
     * @param callbackErr   请求失败回调
     */
    upload:function(type,url,data,callbackSucc,callbackErr){
        var _this = this;
        $.ajax({
            url: url,
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: type,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                $("#loadingImgBox").remove();
                $('body').append(_this.loadingHtml);
            },
            success: function (res) {
                $("#loadingImgBox").remove();
                if(callbackSucc !== undefined) {
                    callbackSucc(res)
                }else{
                    swal(res.message)
                }
            },
            error: function (res) {
                $("#loadingImgBox").remove();
                if(callbackErr) {
                    if (res.status === 401) {
                        setTimeout(function(){
                            $(location).attr('href', 'login.html');
                        },2000)
                    }
                    callbackErr(res)
                }else{
                    console.log(res)
                    if (res.status === 401) {
                        setTimeout(function(){
                            $(location).attr('href', 'login.html');
                        },2000)
                    } else {
                        swal();
                    }
                }
            }
        })
    },

    loadTableData:function(elem,obj){
        $(elem).DataTable({
            data: obj.data,
            destroy: true,
            bLengthChange: false,
            searching: false,
            ordering: false,
            select: false,
            columns: obj.columns,
            pagingType: "full_numbers",
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                oAria: {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            },
            columnDefs: obj.columnDefs
        });
    }

};

/**
 * 清空所选定的表单里的input的显示值
 * @param objForm
 */
function emptyForm(objForm) {
    var input = $(objForm).find("input");
    $(input).each(function (index, obj) {
        $(obj).val("");
    });
}

/**
 * 根据cookie的名称获取一个cookie
 * @param name
 * @returns {*}
 */
function getCookie(name) {
    if (document.cookie.length > 0) {
        var start = document.cookie.indexOf(name + "=");
        if (start !== -1) {
            start = start + name.length + 1;
            var end = document.cookie.indexOf(";", start);
            if (end === -1) {
                end = document.cookie.length;
            }
            return decodeURI(document.cookie.substring(start, end));
        }
    }
    return "";
}

/**
 * 创建一个cookie
 * @param name
 * @param value
 * @param expireDays 缺省值为1
 */
function createCookie(name, value, expireDays) {
    var expires = isNull(expireDays) ? 1 : expireDays;
    var date = new Date();
    date.setDate(date.getDate() + expires);
    document.cookie = name + "=" + decodeURIComponent(value) + ";expires=" + date.toGMTString();
}

/**
 * 检查cookie是否存在
 * @param name
 * @returns {boolean}
 */
function checkCookie(name) {
    var username = getCookie(name);
    return username !== null && username !== "";
}

/**
 * 删除一个cookie
 * @param name
 */
function deleteCookie(name) {
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    document.cookie = name + "=v;expires=" + date.toGMTString();
}

function initPage(obj,url) {
    sessionStorage.setItem('obj',obj);
    $('.treeview-menu >li').removeClass('active');
    $('#'+obj).parent().addClass('active');
    $('.treeview').removeClass('active menu-open')
    $('#'+obj).parents('.treeview').addClass('active menu-open')
    sessionStorage.setItem('firstUrl',url);
    $('#iframe').load('src/pages/'+sessionStorage.getItem('firstUrl'))
}

function delRepeat(arr){
    var ret = [], end;
    arr.sort();
    end = arr[0];
    ret.push(arr[0]);
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] != end) {
            ret.push(arr[i]);
            end = arr[i];
        }
    }

    return ret;
}




